$(document).ready(function() {
    // 内存监控相关变量
    let memoryChart = null;
    let processChart = null;
    let memoryTimer = null;
    const maxDataPoints = 30;
    let memoryData = [];
    let timeData = [];
    let processData = [];

    // 初始化内存监控图表
    function initMemoryCharts() {
        // 总体内存趋势图
        const trendChartDom = document.getElementById('memoryTrendChart');
        memoryChart = echarts.init(trendChartDom);
        
        const trendOption = {
            grid: {
                top: 30,
                right: 20,
                bottom: 30,
                left: 60
            },
            tooltip: {
                trigger: 'axis',
                formatter: function(params) {
                    const memory = params[0].value;
                    return `${params[0].axisValue}<br/>
                            总内存使用: ${formatMemorySize(memory)}`;
                }
            },
            xAxis: {
                type: 'category',
                data: timeData,
                axisLabel: {
                    formatter: function(value) {
                        return value.substring(value.indexOf(' ') + 1);
                    }
                }
            },
            yAxis: {
                type: 'value',
                name: '内存使用',
                axisLabel: {
                    formatter: function(value) {
                        return formatMemorySize(value);
                    }
                }
            },
            series: [{
                name: '内存使用',
                type: 'line',
                smooth: true,
                data: memoryData,
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: 'rgba(102, 126, 234, 0.5)'
                    }, {
                        offset: 1,
                        color: 'rgba(118, 75, 162, 0.1)'
                    }])
                },
                lineStyle: {
                    width: 2,
                    color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [{
                        offset: 0,
                        color: '#667eea'
                    }, {
                        offset: 1,
                        color: '#764ba2'
                    }])
                },
                itemStyle: {
                    color: '#667eea',
                    borderWidth: 2
                }
            }]
        };
        
        memoryChart.setOption(trendOption);

        // 进程内存占用饼图
        const processChartDom = document.getElementById('processChart');
        processChart = echarts.init(processChartDom);
        
        const processOption = {
            tooltip: {
                trigger: 'item',
                formatter: function(params) {
                    return `${params.name}<br/>
                            内存占用: ${formatMemorySize(params.value)}<br/>
                            占比: ${params.percent}%`;
                }
            },
            legend: {
                orient: 'vertical',
                right: 10,
                top: 'center',
                formatter: function(name) {
                    const data = processOption.series[0].data;
                    const item = data.find(item => item.name === name);
                    return `${name}: ${formatMemorySize(item.value)}`;
                }
            },
            series: [{
                name: '进程内存',
                type: 'pie',
                radius: ['40%', '70%'],
                center: ['35%', '50%'],
                avoidLabelOverlap: true,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false
                },
                emphasis: {
                    label: {
                        show: true,
                        formatter: '{b}: {d}%'
                    }
                },
                data: []
            }]
        };
        
        processChart.setOption(processOption);
    }

    // 更新内存数据
    function updateMemoryData() {
        const now = new Date();
        const timeStr = now.toLocaleTimeString();
        
        if (performance && performance.memory) {
            const totalMemory = performance.memory.usedJSHeapSize;
            
            memoryData.push(totalMemory);
            timeData.push(timeStr);
            
            if (memoryData.length > maxDataPoints) {
                memoryData.shift();
                timeData.shift();
            }
            
            memoryChart.setOption({
                xAxis: {
                    data: timeData
                },
                series: [{
                    data: memoryData
                }]
            });

            const processes = [
                { name: '浏览器内核', value: totalMemory * 0.4 },
                { name: 'JavaScript引擎', value: totalMemory * 0.25 },
                { name: 'DOM渲染', value: totalMemory * 0.15 },
                { name: '网络请求', value: totalMemory * 0.1 },
                { name: '插件进程', value: totalMemory * 0.05 },
                { name: '其他', value: totalMemory * 0.05 }
            ];

            processChart.setOption({
                series: [{
                    data: processes
                }]
            });
        }
    }

    // 格式化内存大小
    function formatMemorySize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 监控按钮点击事件
    $('.monitor-btn').on('click', function() {
        const $btn = $(this);
        const $container = $('.memory-chart-container');
        
        if ($container.hasClass('show')) {
            $container.removeClass('show');
            $btn.removeClass('active');
            
            if (memoryTimer) {
                clearInterval(memoryTimer);
                memoryTimer = null;
            }
            
            memoryData = [];
            timeData = [];
            processData = [];
        } else {
            $container.addClass('show');
            $btn.addClass('active');
            
            if (!memoryChart || !processChart) {
                initMemoryCharts();
            }
            
            updateMemoryData();
            memoryTimer = setInterval(updateMemoryData, 1000);
        }
    });

    // 关闭按钮点击事件
    $('.chart-close').on('click', function() {
        $('.monitor-btn').click();
    });

    // 窗口大小改变时调整图表大小
    $(window).on('resize', function() {
        if (memoryChart) {
            memoryChart.resize();
        }
        if (processChart) {
            processChart.resize();
        }
    });
}); 